/**
 *  学习目标：Todos 案例 ts - redux
 *  需求
 *    1. 创建redux仓库
 *      1.1 下包
 *      1.2 创建文件结构  src/store/index.ts  src/store/reducer/todo.ts  src/store/reducer/index.ts
 *      1.3 初始化todoReducer， 合并为rootReducer
 *      1.4 创建store
 *      1.5 和React绑定在一起
 *      1.6 能在App中获取state算成功
 */
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useAppSelector } from './store';
import {
  addTodo,
  checkAllTodo,
  clearIsDoneTodo,
  delTodoById,
  updateTodoById,
  updateType,
} from './store/action/todo';
import './styles/base.css';
import './styles/index.css';

export default function App() {
  const { list, type } = useAppSelector((state) => state.todo);
  // 14.1 在App中监听list，type的变化
  useEffect(() => {
    // 14.2 每次变化，将最新的值存到缓存中
    localStorage.setItem('todo-list', JSON.stringify(list));
    localStorage.setItem('todo-type', type);
  }, [list, type]);

  return (
    <section className="todoapp">
      {/* 头部 */}
      <Header></Header>
      {/* 主体 */}
      <Main></Main>
      {/* 底部 */}
      <Footer></Footer>
    </section>
  );
}
function Footer() {
  const dispatch = useDispatch();
  const { list, type } = useAppSelector((state) => state.todo);
  const listlen = list.filter((item) => !item.isDone).length;

  return (
    <footer className="footer">
      <span className="todo-count">
        <strong>{listlen}</strong> 剩余
      </span>
      <ul className="filters">
        <li>
          <a
            onClick={() => dispatch(updateType('all'))}
            className={type === 'all' ? 'selected' : ''}
            href="#/"
          >
            全部
          </a>
        </li>
        <li>
          <a
            onClick={() => dispatch(updateType('active'))}
            className={type === 'active' ? 'selected' : ''}
            href="#/active"
          >
            未完成
          </a>
        </li>
        <li>
          <a
            onClick={() => dispatch(updateType('completed'))}
            className={type === 'completed' ? 'selected' : ''}
            href="#/completed"
          >
            已完成
          </a>
        </li>
      </ul>
      {/* 7.5 触发dispatch */}
      <button
        className="clear-completed"
        onClick={() => dispatch(clearIsDoneTodo())}
      >
        清除已完成
      </button>
    </footer>
  );
}

function Main() {
  // 1.6验证获取state
  // 3.2 useAppSelector 替换掉useSelector
  const { list, type } = useAppSelector((state) => state.todo);
  const dispatch = useDispatch();
  const showlist = list.filter((item) => {
    if (type === 'all') return true;
    if (type === 'active') return !item.isDone;
    return item.isDone;
  });
  // 15.1 通过计算属性计算小选矿的选中状态得到isAll
  const isAll = list.length ? list.every((item) => item.isDone) : false;
  return (
    <section className="main">
      <input
        id="toggle-all"
        className="toggle-all"
        type="checkbox"
        checked={isAll}
        onChange={(e) => dispatch(checkAllTodo(e.target.checked))}
      />
      {/* // 15.2 将isAll绑定在全选按钮上 */}
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {showlist.map((item) => {
          return (
            <li className={item.isDone ? 'completed' : ''} key={item.id}>
              <div className="view">
                <input
                  className="toggle"
                  type="checkbox"
                  checked={item.isDone}
                  onChange={() => dispatch(updateTodoById(item.id))}
                />
                <label>{item.task}</label>
                <button
                  className="destroy"
                  onClick={() => dispatch(delTodoById(item.id))}
                ></button>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}

function Header() {
  const [task, setTask] = useState('');
  const dispatch = useDispatch();
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // 12.3 非空判断
    if (!task.trim() && e.key === 'Enter') {
      return alert('不能为空');
    }

    // 12.4 监听回车事件
    if (e.key === 'Enter') {
      // 13.4 dispatch触发Action
      dispatch(addTodo(task));
      setTask('');
    }

    // 12.5 监听Esc按键
    if (e.key === 'Escape') {
      setTask('');
    }
  };
  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
        onChange={(e) => setTask(e.target.value)}
        onKeyDown={handleKeyDown}
      />
    </header>
  );
}
